package com.library.controller;

import java.io.IOException;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.library.bean.Book;
import com.library.service.BookService;
import com.library.service.impl.BookServiceImpl;

@MultipartConfig
@WebServlet("/insertBook.do")
public class InsertBookServlet extends HttpServlet{

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		BookService bookService = new BookServiceImpl();
		String bookName = request.getParameter("bookName");
		String bookType = request.getParameter("bookType");
		String bookWriter = request.getParameter("bookWriter");
		double bookPrice = Double.parseDouble(request.getParameter("bookPrice"));
		String pubDate = request.getParameter("pubDate");
		DateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
		Date date = null;
		try {
			date = dft.parse(pubDate);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Part part = request.getPart("bookCover");
		String bookCover = ""; //访问路径
		if(part == null ||part.getSize()>2*1024*1024 || !part.getContentType().contains("image")) {
			request.setAttribute("msg", "请选择2M以内的图片文件作为封面");
			request.getRequestDispatcher("insertBook.jsp");
		}else {
			//设置 图片 保存的地址
//			String savePath = request.getServletContext().getRealPath("/headImgs/");
			String savePath = "C:/bookCoverImgs/";
			//获取一个 独一无二的文件名
			String fileName = "book_"+new Date().getTime()+"_"+part.getSubmittedFileName();
			//上传文件 需要复制到服务器的真实路径（真实路径不在 Tomcat里，需要配置虚拟路径）
			part.write(savePath+fileName);
			// 用于存 访问路径 (如果文件保存在项目之外，注意配置虚拟路径)
			bookCover = "/library/bookCover/"+fileName;
		}
		
		Book book = new Book(bookName, bookType, bookWriter, bookPrice, date,bookCover);
		int result = bookService.insertBook(book);
		response.sendRedirect("showBook.do");
		
	}
	
}
